package org.vacoor.xqq.ui.chat;

import org.vacoor.xqq.ui.dynamictree.Buddy;
import org.vacoor.xqq.ui.comp.tabpane.QuickOpTabbedPane;
import org.vacoor.xqq.ui.util.WindowMoveHandler;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.*;

/**
 * User: vacoor
 */
public class UIChatManager extends JFrame implements ChatManager {
    private static final String TITLE = "X-QQ Chat";
    private static final String NEW_MSG_TITLE = "有新消息";
    private static final Color BACKGROUND_COLOR = new Color(0xE0EFF6);
    private static final Color NEW_MSG_TAB_COLOR = new Color(0xFFAA25);

    private QuickOpTabbedPane quickOpTabbedPane;
    private Timer titleFlasher = new Timer(300, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            UIChatManager c = UIChatManager.this;
            String title = c.getTitle();
            c.setTitle(title == null || c.getTitle().length() == 0 ? NEW_MSG_TITLE : null);
        }
    });

    public UIChatManager() {
        this.setIconImage(new ImageIcon(
                getClass().getClassLoader().getResource("images/qq19x19.png")
        ).getImage());
        init();
    }

    private void init() {
        quickOpTabbedPane = new QuickOpTabbedPane(SwingConstants.TOP, JTabbedPane.WRAP_TAB_LAYOUT);

        quickOpTabbedPane.setOpaque(true);
        quickOpTabbedPane.setBorder(BorderFactory.createLineBorder(new Color(0x777777)));
        quickOpTabbedPane.setBackground(BACKGROUND_COLOR);
        quickOpTabbedPane.setEnabledTabDBClickClose(true);
        quickOpTabbedPane.setEnabledTabQuickSwitch(true);
        quickOpTabbedPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.ALT_DOWN_MASK), "CloseTab");
        quickOpTabbedPane.getActionMap().put("CloseTab", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int idx = quickOpTabbedPane.getSelectedIndex();
                if(idx > -1) {
                    quickOpTabbedPane.removeTabAt(idx);
                }
                if(quickOpTabbedPane.getTabCount() == 0) {
                    setVisible(false);
                }
            }
        });

        this.setContentPane(quickOpTabbedPane);
        this.setTitle(TITLE);
        this.setUndecorated(true);
        this.setSize(new Dimension(500, 450));
        this.setLocationRelativeTo(null);

        new WindowMoveHandler().bindWindowMoveHanderTo(quickOpTabbedPane);

        // 获取光标清理闪烁
        this.addWindowFocusListener(new WindowAdapter() {
            @Override
            public void windowGainedFocus(WindowEvent e) {
                titleFlasher.stop();
                setTitle(TITLE);
            }
        });

        quickOpTabbedPane.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                int idx = quickOpTabbedPane.getSelectedIndex();
                if (0 > idx) {
                    return;
                }
                // 取消选中标签页的唤醒
                quickOpTabbedPane.setBackgroundAt(idx, BACKGROUND_COLOR);

                if (quickOpTabbedPane.getSelectedComponent() instanceof UIChat) {
                    UIChat cp = (UIChat) quickOpTabbedPane.getSelectedComponent();
                    cp.requestFocusForInput();
                }
            }
        });
    }

    @Override
    public Chat getChat(Buddy buddy, boolean create) {
        UIChat UIChat = getChatPanel(buddy.getId());
        if (UIChat == null && create) {
            UIChat = createChatPanel(buddy);
        }
        return UIChat;
    }

    @Override
    public Chat getCurrentChat() {
        return (UIChat) quickOpTabbedPane.getSelectedComponent();
    }

    @Override
    public void setCurrentChat(Chat chat) {
        if (chat == null) {
            return;
        }
        UIChat c = (UIChat) chat;
        quickOpTabbedPane.setSelectedComponent(c);
//        if (!this.isVisible()) {
            this.setVisible(true);
//        }
    }

    @Override
    public void notifyUser(Chat chat) {
        if (chat == null || !(chat instanceof UIChat)) {
            return;
        }
        UIChat c = ((UIChat) chat);
        int idx = quickOpTabbedPane.indexOfComponent(c);
        if (0 > idx) {
            return;
        }

        // 如果当前窗口没有激活
        if (!this.isActive()) {
            titleFlasher.start();
        }

        // 如果不是当前聊天 Tab
        if (chat != getCurrentChat()) {
            quickOpTabbedPane.setBackgroundAt(idx, NEW_MSG_TAB_COLOR);
        }
    }

    @Override
    public void cancelNotify(Chat chat) {
    }


    /**
     * 获取给定联系人id 对应的 面板, 如果不存在返回null
     */
    protected UIChat getChatPanel(long id) {
        for (int i = 0; i < quickOpTabbedPane.getTabCount(); i++) {
            Component c = quickOpTabbedPane.getComponent(i);
            if (!(c instanceof UIChat)) {
                continue;
            }
            UIChat cp = (UIChat) c;
            if (id == cp.getBuddy().getId()) {
                return cp;
            }
        }
        return null;
    }

    /**
     */
    protected UIChat createChatPanel(Buddy buddy) {
        UIChat UIChat = new UIChat(buddy);
        String title = buddy.getMark();
        if (title == null || title.length() < 1) {
            title = buddy.getNick();
        }

        quickOpTabbedPane.addTab(title, UIChat);
        return UIChat;
    }
}
